﻿<%@ Page Language="C#" AutoEventWireup="false" CodeFile="recInvoiceform.aspx.cs"
    Inherits="SIPO.Web.Forms.Transaction.recInvoiceform" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Tagihan Form</title>

    <script src="<%= ResolveUrl("~/scripts/helper.js") %>" type="text/javascript"></script>
    <script src="<%= ResolveUrl("~/scripts/jquery.validate.min.js") %>" type="text/javascript"></script>
    <script src="<%= ResolveUrl("~/scripts/jquery.validate.wrapper.js") %>" type="text/javascript"></script>

    <%-- Jquery stuffs start --%>
    <link type="text/css" rel="stylesheet" href="<%= ResolveUrl("~/styles/ui.jqgrid.css") %>" />
    <script type="text/javascript" src="<%= ResolveUrl("~/scripts/i18n/grid.locale-id.js") %>"></script>
    <script type="text/javascript" src="<%= ResolveUrl("~/scripts/jquery.jqGrid.min.js") %>"></script>

     <style type="text/css">
  .custom-combobox {
    position: relative;
    display: inline-block;
  }
  .custom-combobox-toggle {
    position: absolute;
    top: 0;
    bottom: 0;
    margin-left: -1px;
    padding: 0;
    /* support: IE7 */
    height: 1.7em;
    top: 0.1em;
  }
  .custom-combobox-input {
    margin: 0;
    padding: 0.3em;
  }
         .style1
         {
             width: 225px;
         }
         .style2
         {
             width: 111px;
         }
  </style>

     <script type="text/javascript" language="javascript">

         (function ($) {

             $.widget("custom.combobox", {
                 _create: function () {
                     this.wrapper = $("<span>")
          .addClass("custom-combobox")
          .insertAfter(this.element);

                     this.element.hide();
                     this._createAutocomplete();
                     this._createShowAllButton();
                 },

                 _createAutocomplete: function () {
                     var selected = this.element.children(":selected"),
          value = selected.val() ? selected.text() : "";

                     var width = this.element.width() > 100 ? "style='width:" + this.element.width() + "px';" : "";

                     this.input = $("<input " + width + ">")
          .appendTo(this.wrapper)
          .val(value)
          .attr("title", "")
          .addClass("custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left")
          .autocomplete({
              autoFocus: true,
              selectFirst: true,
              delay: 0,
              minLength: 0,
              source: $.proxy(this, "_source")
          })
          .tooltip({
              tooltipClass: "ui-state-highlight"
          });

                     this._on(this.input, {
                         autocompleteselect: function (event, ui) {
                             ui.item.option.selected = true;
                             this._trigger("select", event, {
                                 item: ui.item.option
                             });

                             var idOfCaller = this.element.attr('id');
                             switch (idOfCaller.toLowerCase()) {
                                 case ("ddlsector"):
                                     $('#ddlSector').change();
                                     break;
                                 case ("ddlsubsector"):
                                     $('#ddlSubSector').change();
                                     break;
                                 case ("ddlsubsubsector"):
                                     $('#ddlSubSubSector').change();
                                     break;
                                 default:
                                     break;
                             }

                         },

                         autocompletechange: "_removeIfInvalid"
                     });
                 },

                 _createShowAllButton: function () {
                     var input = this.input,
          wasOpen = false;

                     $("<a>")
          .attr("tabIndex", -1)
          .attr("title", "Tamplikan Semua Item")
          .tooltip()
          .appendTo(this.wrapper)
          .button({
              icons: {
                  primary: "ui-icon-triangle-1-s"
              },
              text: false
          })
          .removeClass("ui-corner-all")
          .addClass("custom-combobox-toggle ui-corner-right")
          .mousedown(function () {
              wasOpen = input.autocomplete("widget").is(":visible");
          })
          .click(function () {
              input.focus();

              // Close if already visible
              if (wasOpen) {
                  return;
              }

              // Pass empty string as value to search for, displaying all results
              input.autocomplete("search", "");
          });
                 },

                 _source: function (request, response) {
                     var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
                     response(this.element.children("option").map(function () {
                         var text = $(this).text();
                         if (this.value && (!request.term || matcher.test(text)))
                             return {
                                 label: text,
                                 value: text,
                                 option: this
                             };
                     }));
                 },

                 _removeIfInvalid: function (event, ui) {

                     // Selected an item, nothing to do
                     if (ui.item) {
                         return;
                     }

                     // Search for a match (case-insensitive)
                     var value = this.input.val(),
          valueLowerCase = value.toLowerCase(),
          valid = false;
                     this.element.children("option").each(function () {
                         if ($(this).text().toLowerCase() === valueLowerCase) {
                             this.selected = valid = true;
                             return false;
                         }
                     });

                     // Found a match, nothing to do
                     if (valid) {
                         return;
                     }

                     // Remove invalid value
                     this.input
          .val("")
          .attr("title", value + " tidak ditemukan")
          .tooltip("open");
                     this.element.val("");
                     this._delay(function () {
                         this.input.tooltip("close").attr("title", "");
                     }, 2500);
                     this.input.data("ui-autocomplete").term = "";
                 },

                 _destroy: function () {
                     this.wrapper.remove();
                     this.element.show();
                 },
                 autocomplete: function (value, text) {
                     this.element.val(value);
                     this.input.val(text);
                 }
             });
         })(jQuery);

         $(function () {

             $("#ddlSector").combobox();
             $("#ddlSubSector").combobox();
             $("#ddlSubSubSector").combobox();

         });

    </script>

    <script type="text/javascript">

        $("#btnSave").button({ icons: { primary: "ui-icon-disk"} });
        $("#btnClose").button({ icons: { primary: "ui-icon-close"} });

    </script>
 
    <script type="text/javascript">

        $(document).ready(function () {

            // 1. prepare the validation rules and messages.
            var rules = {
                ddlSector: "required",
                ddlSubSector: "required",
                ddlSubSubSector: "required"

            };
            var messages = {

                ddlSector: "Sektor harus di isi...",
                ddlSubSector: "Sub Sektor harus di isi...",
                ddlSubSubSector: "Sub Sub Sektor harus di isi..."

            };

            // 2. Initiate the validator
            var validator = new jQueryValidatorWrapper("form1", rules, messages);

            $('#ddlSubSubSector').change(function () {
                loadDebtorSector();
            });



            $('#ddlSubSector').change(function () {
                //refresh grid
                //loadGrid("-1");
            });


            $('#ddlSector').change(function () {
                loadGrid("-1");
                getSubSector();
                
            });




            $("#btnSave").click(function () {

                if (!validator.validate())
                    return;

                var grid = $('#tableDetail');
                var selIds = grid.jqGrid('getGridParam', 'selarrrow'),
                selText = [];
                $.each(selIds, function () {
                    selText.push(grid.jqGrid('getCell', this, 'BillingNo'));
                });

                if (selIds.length == 0) {
                    alert('Pilih satu record untuk simpan data.');
                }
                else if (selIds.length >= 1) {
                    //ambil sectorID dan SubSectorID buat format No Invoice
                    var sectorCode = $("#ddlSector option:selected").text().split("-")[0].trim();
                    var subsectorCode = $("#ddlSubSector option:selected").text().split("-")[0].trim();

                    var objrecBilling = new Object();
                    objrecBilling.BillingNo = encodeURIComponent(selText);
                    jsonData = JSON.stringify(objrecBilling);

                    var handlerUrl = '<%= ResolveUrl("~/ajaxhandler/transaction/recInvoicehandler.ashx") %>';

                    $.ajax({
                        type: 'POST',
                        url: handlerUrl + "?method=insert&sectorCode=" + sectorCode + "&subsectorCode=" + subsectorCode,
                        contentType: 'application/json',
                        dataType: 'json',
                        data: jsonData,
                        success: function (data) {
                            if (data.IsSuccess) {

                                parent.$('#dialog').dialog('close');
                                setTimeout("parent.$('#table').trigger('reloadGrid');", 3000);
                                alert(data.Message);
                                window.open('../../reports/Transaction/rptInvoice.aspx?InvoiceNo=' + data.Data, 'popUpWindow', 'height=400,width=800,left=300,top=200,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no, status=yes');
                            }
                            else {
                                alert(data.Message);
                            }
                        },
                        error: function (response) {
                            var r = JSON.parse(response.responseText);
                            alert("Error Message: " + r.Message);
                        }
                    });



                }
            });

            getSector();

        });


        function getSector() {
            var subsubsectors = "<%= base.SubSubSectorIDs %>";
            var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getsector.ashx?method=getbysubsubsectorIDs") %>';
            $sector = $('#ddlSector');
            $.ajax({
                type: 'POST',
                url: handlerUrl + "&subsubsectorids=" + subsubsectors,
                contentType: 'application/json',
                dataType: 'json',
                success: function (datas) {
                    if (datas.length > 1) {
                        $sector.get(0).options[0] = new Option("-- pilih sektor --", "");
                        $.each(datas, function (i, data) {
                            $sector.append('<option value="' + data.SectorID + '">' + data.SectorCode + ' - ' + data.SectorName + '</option>');
                        });
                        $sector.combobox('autocomplete', "", "-- pilih sektor --");
                    }
                    else {
                        $sector.append('<option value="' + datas[0].SectorID + '">' + datas[0].SectorCode + ' - ' + datas[0].SectorName + '</option>');
                        $sector.combobox('autocomplete', datas[0].SectorID, datas[0].SectorCode + ' - ' + datas[0].SectorName);

                        getSubSector();
                    }
                },
                error: function () {
                    alert('Error load data sektor!');
                }
            });
        }

        function getSubSector() {
            var sectorId = $("#ddlSector option:selected").val();
            $subSectors = $('#ddlSubSector');
            $subSubSectors = $('#ddlSubSubSector');

            //$sector = $('#ddlSector');
            //$subsector = $('#ddlSubSector');
            //$subsubsector = $('#ddlSubSubSector');
            //$sector.combobox('autocomplete', "", "-- pilih sektor --");
           //$subSectors.combobox('autocomplete', "", "-- pilih sub sektor --");
            //$subSubSectors.combobox('autocomplete', "", "-- pilih sub sub sektor --");


            //refreshgrid
            //loadGrid("-1");
            if (sectorId > 0) {
                var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getsubsector.ashx?method=getbysectorid_AND_subsubsectorids&sector_id=") %>';

                $.ajax({
                    type: 'POST',
                    url: handlerUrl + sectorId,
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function (datas) {
                        if (datas.length > 1) {
                            $subSectors.get(0).options.length = 0;
                            $subSectors.get(0).options[0] = new Option("-- pilih sub sektor --", "");

                            $subSubSectors.get(0).options.length = 0;
                            $subSubSectors.get(0).options[0] = new Option("-- pilih sub sub sektor --", "");

                            $.each(datas, function (i, data) {
                                $subSectors.append('<option value="' + data.SubSectorID + '">' + data.SubSectorCode + '-' + data.SubSectorName + '</option>');
                            });

                            $subSectors.combobox('autocomplete', "", "-- pilih sub sektor --");

                        }
                        else {

                            //$subSectors.combobox('autocomplete', "", "-- pilih sub sektor --");
                            $subSectors.get(0).options.length = 0;
                            $subSectors.get(0).options[0] = new Option("-- pilih sub sektor --", "");
                            $subSectors.append('<option value="' + datas[0].SubSectorID + '">' + datas[0].SubSectorCode + ' - ' + datas[0].SubSectorName + '</option>');
                            $subSectors.combobox('autocomplete', datas[0].SubSectorID, datas[0].SubSectorCode + ' - ' + datas[0].SubSectorName);
                            GetSubSubSector(datas[0].SubSectorID);

                        }

                        $subSectors.bind("change", function () {
                            GetSubSubSector($(this).val());
                        });
                    },
                    error: function () {
                        alert('Error!');
                    }
                });
            }
            else {
                $subSectors.get(0).options.length = 0;
                $subSectors.get(0).options[0] = new Option("-- pilih sub sektor --", "");
                $subSubSectors.get(0).options.length = 0;
                $subSubSectors.get(0).options[0] = new Option("-- pilih sub sub sektor --", "");
            }
        }

        function GetSubSubSector(subsectorID) {
            $subSubSectors = $('#ddlSubSubSector');
            if (subsectorID > 0) {
                var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getsubsubsector.ashx?method=getbysubsectorid_AND_subsubsectorids&subsector_id=") %>';
                $.ajax({
                    type: 'POST',
                    url: handlerUrl + subsectorID,
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function (datas) {
                        if (datas.length > 1) {
                            $subSubSectors.get(0).options.length = 0;
                            $subSubSectors.get(0).options[0] = new Option("-- pilih sub sub sektor --", "");

                            $.each(datas, function (i, data) {
                                $subSubSectors.append('<option value="' + data.SubSubSectorID + '">' + data.SubSubSectorCode + '-' + data.SubSubSectorName + '</option>');
                            });

                            $subSubSectors.combobox('autocomplete', "", "-- pilih sub sub sektor --");
                        }
                        else {

                            $subSubSectors.get(0).options.length = 0;
                            $subSubSectors.get(0).options[0] = new Option("-- pilih sub sub sektor --", "");
                            $subSubSectors.append('<option value="' + datas[0].SubSubSectorID + '">' + datas[0].SubSubSectorCode + ' - ' + datas[0].SubSubSectorName + '</option>');
                            $subSubSectors.combobox('autocomplete', datas[0].SubSubSectorID, datas[0].SubSubSectorCode + ' - ' + datas[0].SubSubSectorName);
                            loadDebtorSector();
                        }
                    },
                    error: function () {
                        $subSubSectors.get(0).options.length = 0;
                        alert("Gagal isi sub sub sector");
                    }
                });
            }
            else {
                $subSubSectors.get(0).options.length = 0;
                $subSubSectors.get(0).options[0] = new Option("-- pilih sub sub sektor --", "");
            }
        }

        function loadGrid(DebtorSectorID) {
           // alert(DebtorSectorID);
            var handlerUrlInvoice = '<%= ResolveUrl("~/AjaxHandler/Transaction/recBillinghandler.ashx") %>';
            $('#tableDetail').setGridParam({ url: handlerUrlInvoice + "?method=getdatainvoice&DebtorSectorID=" + DebtorSectorID });
            $('#tableDetail').trigger('reloadGrid');

        }

        function loadDebtorSector() {

            var debtor_id = "<%= base.DebtorID %>";
            var sector_id = $("#ddlSector option:selected").val();
            var subsector_id = $("#ddlSubSector option:selected").val();
            var subsubsector_id = $("#ddlSubSubSector option:selected").val();
            var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Loaddata/getdebtorsector.ashx?method=getdatabyparaminvoice") %>';
            //if (debtor_id != "") {
                var debtorsectorID = "-1";
                $.ajax({
                    type: 'POST',
                    url: handlerUrl + "&debtor_id=" + debtor_id + "&sector_id=" + sector_id + "&subsector_id=" + subsector_id + "&subsubsector_id=" + subsubsector_id,
                    contentType: 'application/json',
                    dataType: 'json',
                    success: function (datas) {
                        $.each(datas, function (i, data) {
                            debtorsectorID = data.DebtorSectorID;
                        });
                       // alert(debtorsectorID);
                        loadGrid(debtorsectorID);
                    },
                    error: function () {
                        alert("Gagal load data debtorsector");
                    }
                });
            //}
            //else {
            //    alert("User login tidak terdaftar sebagai Debitur sehingga tidak bisa load data tagihan !");
           // }

        }

    </script>
    <script type="text/javascript">

        $('#btnClose').click(function () {

            parent.$('#dialog').dialog('close');

            return false;
        });
        
         
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <table border="0">
      <%--  <tr>
            <td style="width: 50">
                No Invoice
            </td>
            <td>
                :
            </td>
            <td>
                <asp:TextBox ID="txtInvoiceNo" runat="server" Width="100"></asp:TextBox>
            </td>
        </tr>--%>
        <tr>
            <td style="width: 50">
                Tgl. Surat Setoran
            </td>
            <td>
                :
            </td>
            <td>
                <asp:TextBox ID="txtInvoiceDate" Enabled="false" runat="server" Width="100"></asp:TextBox>
            </td>
        </tr>
         <tr>
            <td style="width: 50">
                Sektor
            </td>
            <td>
                :
            </td>
            <td>
                <asp:DropDownList ID="ddlSector" runat="server" Width="300">
                </asp:DropDownList>
                &nbsp;<span style="color: Red;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *</span>
            </td>
        </tr>
        <tr>
            <td style="width: 50">
                Sub Sektor
            </td>
            <td>
                :
            </td>
            <td>
                <asp:DropDownList ID="ddlSubSector" runat="server" Width="300">
                </asp:DropDownList>
                &nbsp;<span style="color: Red;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *</span>
            </td>
        </tr>
        <tr>
            <td style="width: 50">
                Sub Sub Sektor
            </td>
            <td>
                :
            </td>
            <td>
                <asp:DropDownList ID="ddlSubSubSector" runat="server" Width="300">
                </asp:DropDownList>
                &nbsp;<span style="color: Red;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; *</span>
            </td>
        </tr>
        <tr>
            <td colspan="2">
                &nbsp;
            </td>
            <td>
                <asp:HiddenField ID="hfID" runat="server" />
                <asp:HiddenField ID="hfInvoiceNo" runat="server" />
            </td>
        </tr>
    </table>
    <br />
    <table id="tableDetail" class="scroll" cellpadding="0" cellspacing="0">
    </table>
    <div id="pagerDetail" class="scroll">
    </div>
    <br />
    <div id="dialogDetail" title="Default dialog">
    </div>
    <script type="text/javascript">
        $(document).ready(function () {
            var handlerUrl = '<%= ResolveUrl("~/AjaxHandler/Transaction/recBillinghandler.ashx?method=nomethod") %>';

            $('#tableDetail').jqGrid({
                url: handlerUrl,
                datatype: 'json',
                colNames: ['ID', 'InvoiceNo', 'Jenis Tagihan', 'Keterangan', 'Jatuh Tempo', 'Nilai Tagihan'],
                colModel: [
                            { name: 'BillingNo', key: true, hidden: true, index: 'BillingNo', width: 60 },
                            { name: 'InvoiceNo', hidden: true, index: 'InvoiceNo', width: 60 },
           		            { name: 'recTransactionType.TransTypeName', index: 'recBilling.TransTypeID', width: 200, searchoptions: { sopt: ['eq', 'cn']} },
                            { name: 'ForPayment', index: 'ForPayment', align: 'left', width: 200, searchoptions: { sopt: ['eq', 'cn']} },
                            { name: 'DueDate', index: 'DueDate', align: 'center', width: 100, searchoptions: { sopt: ['eq', 'cn'] }, formatter: 'date', formatoptions: { newformat: 'd M Y'} },
                            { name: 'Value', index: 'Value', formatter: 'currency', align: 'right', formatoptions: { decimalSeparator: ".", thousandsSeparator: ",", decimalPlaces: 2 }, width: 150, searchoptions: { sopt: ['eq', 'cn']} }
           	            ],
                rowNum: 10,
                id: 'BillingNo',
                multiselect: true,
                rowList: [5, 10, 15, 20],
                pager: '#pagerDetail',
                sortname: 'recBilling.TransTypeID',
                sortorder: "asc",
                viewrecords: true,
                jsonReader: { repeatitems: false },
                width: 800,
                height: '100%',
                caption: 'Tagihan',
                ajaxGridOptions: { cache: false }

            });

            $("#tableDetail").jqGrid('navGrid', '#pagerDetail', { edit: false, add: false, del: false, searchtext: 'Search', refreshtext: 'Refresh' },
                    {}, {}, {}, { closeOnEscape: true, multipleSearch: true, closeAfterSearch: true });



        });
    </script>
    <div>
        <div style="text-align: right; padding-top: 10px;">
            <button id="btnSave" type="button">
                Save</button>
            <button id="btnClose" type="button">
                Close</button>
        </div>
    </div>
    </form>
</body>
</html>
